﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.EventSystems;
using UnityEngine.UI;

namespace Miao.UI
{
    /// <summary>
    /// 可对UI自由进行拖拽
    /// </summary>
    public class DragAndDrop : DragBase
    {
        public Vector2 originalLocalPointerPosition;//offSet
        private Vector3 originalPanelLocalPosition;
        public Graphic graphic;

        //public Action<Vector3> onBeginDrag;
        //public Action<Vector3> onDrag;
        //public Action<Vector3> onEndDrag;
        public void Reset()
        {
            graphic = GetComponent<Graphic>();
        }

        protected override void Awake()
        {
            base.Awake();
            originalPanelLocalPosition = transform.localPosition;
        }

        public override void OnBeginDrag(PointerEventData eventData)
        {
            originalPanelLocalPosition = transform.localPosition;
            RectTransformUtility.ScreenPointToLocalPointInRectangle(canvasRectTransform, eventData.position, eventData.pressEventCamera, out originalLocalPointerPosition);
            //onBeginDrag?.Invoke(eventData.position);
        }


        
        public override void OnDrag(PointerEventData eventData)
        {
            //rectTransform.position = Camera.main.WorldToViewportPoint(eventData.position);
            Vector2 localPointerPosition;//拖拽时鼠标指针的本地坐标+
            if (RectTransformUtility.ScreenPointToLocalPointInRectangle(canvasRectTransform, eventData.position, eventData.pressEventCamera, out localPointerPosition))
            {
                Vector3 offsetToOriginal = localPointerPosition - originalLocalPointerPosition;     //鼠标指针相对位移
                rectTransform.localPosition = originalPanelLocalPosition + offsetToOriginal;   //目标对象位移补偿
                //onDrag?.Invoke(rectTransform.position);
            }
          
        }
        public override void OnEndDrag(PointerEventData eventData)
        {
            //onEndDrag?.Invoke(rectTransform.localPosition);
        }
    }

}